<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { movieAddFormSchema, movieUpdateFormSchema } from './movieData';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { movieAddApi, movieUpdateApi } from '@/api/hopefly/api';
  import { MovieAdd, MovieUpdate } from '@/api/hopefly/model/tableModel';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const id = ref<number>(0);

  const [registerForm, { resetFields, setFieldsValue, validate, resetSchema }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: movieAddFormSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    id.value = data.record?.id;
    // 更新表单配置
    if (unref(isUpdate)) {
      await resetSchema(movieUpdateFormSchema);
      // 设置表单值 - 重新设置表单字段以匹配更新表单的字段结构
      setFieldsValue({
        name: data.record?.name,
        url: data.record?.url,
      });
    } else {
      await resetSchema(movieAddFormSchema);
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增网站' : '编辑网站'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await movieAddApi(values as MovieAdd);
      } else {
        values.id = id.value;
        await movieUpdateApi(id.value, values as MovieUpdate);
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
